# -*- coding: utf-8 -*-
# @desc:
# @file: log_helper.py
# @author: Lin Jackey Lyu (me@linlyu.com)
# @date: 2018/7/26 16:23

import logbook
from logbook.more import ColorizedStderrHandler
import os


def setup_logbook(logfile, logfile_kwargs=None):
    """Return a basic `logbook` setup which logs to `stderr` and to file."""
    dirname = os.path.dirname(logfile)
    if not os.path.exists(dirname):
        # os.makedirs(dirname, exist_ok=True)
        os.makedirs(dirname)

    if logfile_kwargs is None:
        logfile_kwargs = {}

    logfile_kwargs.setdefault('level', 'DEBUG')
    logfile_kwargs.setdefault('mode', 'a')
    logfile_kwargs.setdefault('backup_count', 8)
    logfile_kwargs.setdefault('max_size', 10 * 1024 * 1024)
    logfile_kwargs.setdefault('bubble', True)
    logfile_kwargs.setdefault('format_string',
                              ('--------------------------------------------------------------------------\n'
                               '[{record.time:%Y-%m-%d %H:%M:%S.%f%z} {record.level_name:<8s} {record.channel:>10s}]'
                               ' {record.filename:s}:{record.lineno:d}\n{record.message:s}'))

    # Set the format for the datetime objects created
    logbook.set_datetime_format('local')
    logbook_setup = logbook.NestedSetup([
        logbook.NullHandler(),
        ColorizedStderrHandler(level='INFO', bubble=False,
                               format_string='[{record.time:%Y-%m-%d %H:%M:%S.%f%z} {record.level_name:<8s} {record.channel:s}] {record.message:s}'),
        logbook.RotatingFileHandler(logfile, **logfile_kwargs),
    ])

    return logbook_setup
